
//
//  NetRequestClss.m
//  DataStatistics
//
//  Created by Kang on 15/12/9.
//  Copyright © 2015年 YTYangK. All rights reserved.
//
//  请求格式
//
#import "NetRequestClass.h"
#import <AFNetworking.h>
#import "ACQRDeviceModel.h"
#import "ACDeviceListModelCenter.h"
#import "ACUserLoginManage.h"
#import "UtilToolsClass.h"
#import "LoginVC.h"
#import "PPQueryGpsModel.h"
#import "ACDeviceListModel.h"
#import "ACDeviceDetailModel.h"
#import "ACDeviceInfoModel.h"
#import "LoginVC.h"
@implementation NetRequestClass
#pragma mark -------------- 校验手机号码
+ (void)requestWithUrlForCheckPhoneNumber:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param success:(void (^)(NSInteger))success failure:(void (^)(NSString *))failure{

    [self GetDataForRequestAndBlockResult:url andRequestParam:param andResult:^(id successResult) {
        NSNumber *result = (NSNumber *)[successResult objectForKey:@"body"][@"result"]
        ;
        success([result integerValue]);
    } andFailureBlock:^(NSString *failureResult) {
        NSLog(@"\n服务器连接失败-->error is %@",failureResult);
        failure(failureResult);
    }];
}


#pragma mark 校验 -------------- 校验码
+ (void)requestWithUrlForCheckPhoneMessages:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param success:(void (^)(NSInteger))success failure:(void (^)(NSString *))failure{
    [self GetDataForRequestAndBlockResult:url andRequestParam:param andResult:^(id successResult) {
        NSNumber *result = (NSNumber *)[successResult objectForKey:@"body"][@"result"]
        ;
        if (result) {
            success([result integerValue]);
        }else{
            failure([successResult objectForKey:@"body"][@"error"]);
        }
    } andFailureBlock:^(NSString *failureResult) {
        NSLog(@"\n服务器连接失败-->error is %@",failureResult);
        failure(failureResult);
    }];
}


#pragma mark 用户 -------------- 登录
+ (void)requestWithUrlForLoginIn:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param success:(void (^)(ACUserLoginManage *))success failure:(void (^)(NSString *))failure{

    NSLog(@"%@",url);
    [self GetDataForRequestAndBlockResult:url andRequestParam:param andResult:^(id successResult) {
        int loginResult =  [successResult[@"body"][@"loginResult"] intValue];
          NSString * errorStr = @"";
        if (loginResult == 8) {
            ACUserLoginManage* model = [ACUserLoginManage loginModelWithDic:successResult[@"body"]];
            if (success) {
                //  保存登录的session对象
                [self saveLoginSession];
                success(model);
                return ;
            }
        }else if(loginResult == 0){   // 如下代码恶心的，不想说话了
            errorStr = NSLocalizedString(@"用户名密码为空", nil);
        }else if(loginResult == 1){
            errorStr = NSLocalizedString(@"用户不存在", nil);
        }else if(loginResult == 2){
            errorStr =  NSLocalizedString(@"密码错误", nil) ;
        }else if(loginResult == 3){
            errorStr = NSLocalizedString(@"服务器繁忙", nil);
        }else if(loginResult == 4){
            errorStr = NSLocalizedString(@"验证码错误", nil);
        }else if(loginResult == 5){
            errorStr = NSLocalizedString(@"没有权限", nil);
        }else if(loginResult == 6){
            errorStr = NSLocalizedString(@"停用账号", nil);
        }
        failure(errorStr);
    } andFailureBlock:^(NSString *failureResult) {
        NSLog(@"\n服务器连接失败-->error is %@",failureResult);
        failure(failureResult);
    }];
}


#pragma mark 用户 -------------- 修改用户密码
+ (void)requestWithUrlChangeUserPwd:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param success:(void (^)(NSString *))success failure:(void (^)(NSString *))failure{

    [self GetDataForRequestAndBlockResult:url andRequestParam:param andResult:^(id successResult) {
        int loginResult =  [successResult[@"body"][@"updateResult"] intValue];
        NSString * errorStr = @"";
        if (loginResult == 0) {
            errorStr = @"禁止修改";
        }else if(loginResult == 1){
            errorStr = @"原密码错误";
        }else if(loginResult == 2){
            errorStr = NSLocalizedString(@"修改成功", nil);
        }else if(loginResult == 3){
            errorStr = @"session超时";
        }else if(loginResult == 4){
            errorStr = @"账号不一致";
        }
        success(errorStr);
    } andFailureBlock:^(NSString *failureResult) {
        NSLog(@"\n服务器连接失败-->error is %@",failureResult);
        failure(failureResult);
    }];
}


#pragma mark 用户 -------------- 修改用户信息
/**
 *   此处由于两个请求都采用同一个接口，但返回的格式参数不一致
 */
+ (void)requestWithUrlChangeUserInfo:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param success:(void (^)(NSString *, NSInteger))success failure:(void (^)(NSString *))failure{
    if (![param[@"headImage"] isEqualToString:@""]) {
        
        [self PostDataForRequestAndBlockResult:url andRequestParam:param andUpload:false andResult:^(id successResult) {
            int result =  [successResult[@"body"][@"result"] intValue];
            if (result) {
                success(successResult[@"body"][@"success"],1);
                return ;
            }
            if (!result) {
                failure([NSString stringWithFormat:@"%@",successResult[@"body"][@"error"]]);
            }

         } andFailureBlock:^(NSString *failureResult) {
              failure(failureResult);
        }];
      }else{
          [self PostDataForRequestAndBlockResult:url andRequestParam:param andUpload:false andResult:^(id successResult) {
              int result =  [successResult[@"body"][@"result"] intValue];
              if (result) {
                  success(@"",1);
                  return ;
              }
              if (!result) {
                  failure([NSString stringWithFormat:@"%@",successResult[@"body"][@"error"]]);
              }
          } andFailureBlock:^(NSString *failureResult) {
              failure(failureResult);
          }];
      }
}


#pragma mark 用户 -------------- 注册设置用户密码
+ (void)requestWithUrlForSetPwd:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param success:(void (^)(NSInteger))success failure:(void (^)(NSString *))failure{
    [self GetDataForRequestAndBlockResult:url andRequestParam:param andResult:^(id successResult) {
        int result =  [successResult[@"body"][@"result"] intValue];
        if (result  == 1) {
            success(result);
            return ;
        }
        if (result  == 0) {
            failure([NSString stringWithFormat:@"%@",successResult[@"body"][@"error"]]);
            return ;
        }
        if (result == 2) {
            failure([NSString stringWithFormat:@"已经注册"]);
            return ;
        }
    } andFailureBlock:^(NSString *failureResult) {
        NSLog(@"\n服务器连接失败-->error is %@",failureResult);
        failure(failureResult);
    }];

}



#pragma mark 用户 --------------忘记密码，修改密码
+ (void)requestWithUrlForForgetPwd:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param success:(void (^)(NSInteger))success failure:(void (^)(NSString *))failure{
   
    [self GetDataForRequestAndBlockResult:url andRequestParam:param andResult:^(id successResult) {
        int result =  [successResult[@"body"][@"result"] intValue];
        if (result  == 1) {
            success(result);
            return ;
        }
        if (result  == 0) {
            failure([NSString stringWithFormat:@"%@",successResult[@"body"][@"error"]]);
            return ;
        }

    } andFailureBlock:^(NSString *failureResult) {
        NSLog(@"\n服务器连接失败-->error is %@",failureResult);
        failure(failureResult);
    }];
}

#pragma mark 用户 --------------退出操作
+ (void)requestWithUrlForLogOut:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param success:(void (^)(BOOL))success failure:(void (^)(NSString *))failure{
    
    [self GetDataForRequestAndBlockResult:url andRequestParam:param andResult:^(id successResult) {
        BOOL result = (BOOL)successResult[@"body"][@"result"] ;
        success(result);
    } andFailureBlock:^(NSString *failureResult) {
        NSLog(@"\n服务器连接失败-->error is %@",failureResult);
        failure(failureResult);
    }];


}

#pragma mark 设备 -------------- 显示设备详情
+ (void)requestWithUrlForDeviceDetail:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param success:(void (^)(ACQRDeviceModel *))success failure:(void (^)(NSString *))failure{

    NSLog(@"%@",param);
    
    [self GetDataForRequestAndBlockResult:url andRequestParam:param andResult:^(id successResult) {
        NSDictionary *responeDic  = (NSDictionary *)successResult;
        if (!responeDic.count) {
            failure(@"操作失败");
            return ;
        }
        NSMutableDictionary * tempDic = [responeDic[@"body"] mutableCopy];
        if([tempDic[@"result"] intValue]){
            // 服务器端未加入此设备信息
            failure(NSLocalizedString(@"服务器未检测到该设备信息",nil));
            return;
        }else{
            ACQRDeviceModel * qrModel = [ACQRDeviceModel qrDeviceWithDic:tempDic];
            success(qrModel);
        }
    } andFailureBlock:^(NSString *failureResult) {
        NSLog(@"\n服务器连接失败-->error is %@",failureResult);
        failure(failureResult);
    }];
}

#pragma mark 修改设备信息
+ (void)requestWithUrlForUpdateDeviceInfo:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param success:(void (^)(NSInteger))success failure:(void (^)(NSString *))failure{
    [self PostDataForRequestAndBlockResult:url andRequestParam:param andUpload:false andResult:^(id successResult) {
           success([successResult[@"body"][@"result"] intValue]);
    } andFailureBlock:^(NSString *failureResult) {
        NSLog(@"\n服务器连接失败-->error is %@",failureResult);
        failure(failureResult);
    }];
    
}


#pragma mark 设备 -------------- 获取设备相求
+ (void)requestWithUrlForGetDeviceMessage:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param success:(void (^)(ACDeviceDetailModel *))success failure:(void (^)(NSString *))failure{
    
    [self GetDataForRequestAndBlockResult:url andRequestParam:param andResult:^(id successResult) {
        NSDictionary *responeDic  = (NSDictionary *)successResult;
        if (!responeDic.count) {
            failure(@"操作失败");
            return ;
        }
        NSDictionary * tempDic = responeDic[@"body"];
        ACDeviceDetailModel * qrModel = [ACDeviceDetailModel deviceDetailModelWithDic:tempDic];
        success(qrModel);
    } andFailureBlock:^(NSString *failureResult) {
        NSLog(@"\n服务器连接失败-->error is %@",failureResult);
        failure(failureResult);
    }];
    
}


#pragma mark 设备 -------------- 绑定设备
+ (void)requestWithUrlForBindingDevice:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param success:(void (^)(NSDictionary * ))success failure:(void (^)(NSString *))failure{
    [self PostDataForRequestAndBlockResult:url andRequestParam:param andUpload:false andResult:^(id successResult) {
        NSDictionary *resultDic =  successResult[@"body"];
        
        NSLog(@"%@",resultDic);
        
        if (resultDic.count) {
            success(resultDic);
        }
        
    } andFailureBlock:^(NSString *failureResult) {
        NSLog(@"\n服务器连接失败-->error is %@",failureResult);
        failure(failureResult);
    }];

}

#pragma mark 设备 --------------解除绑定设备
+ (void)requestWithUrlForUnBindingDevice:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param success:(void (^)(NSInteger))success failure:(void (^)(NSString *))failure{
  
    [self GetDataForRequestAndBlockResult:url andRequestParam:param andResult:^(id successResult) {
       int result =  [successResult[@"body"][@"result"] intValue] ; // 0 是成功,1是失败
        if (!result) {
                success(result);
            }else{
                failure(NSLocalizedString(@"设备解绑失败", nil));
            }
        
    } andFailureBlock:^(NSString *failureResult) {
        NSLog(@"\n服务器连接失败-->error is %@",failureResult);
        failure(failureResult);
    }];

}


#pragma mark 设备列表 --------------  获取设备列表的所有数据  state表示的所有、正常、故障
+ (void)requestWithUrlForDviceList:(id)obj andUrl:(NSString *)url andParam:(NSString *)deviceCode andAscendingOrder:(NSString *)ascendingOrder andOrderName:(NSString *)orderName andPage:(NSInteger)current_page andState:(NSInteger)state success:(void (^)(NSDictionary *))success failure:(void (^)(NSString *))failure{
    NSDictionary * param =  param = @{@"current_page":@(current_page),@"mapVo":@{@"code":deviceCode},@"ascendingOrder":ascendingOrder,@"orderName":orderName,@"state":@(state)};
   
    
    [self GetDataForRequestAndBlockResult:url andRequestParam:param andResult:^(id successResult) {
        int result =  [successResult[@"body"][@"result"] intValue];
        if (result) {
            failure(successResult[@"body"][@"deviceList"]);
        }else{
            NSDictionary * resultDic = successResult[@"body"];
                success(resultDic);
            }
          } andFailureBlock:^(NSString *failureResult) {
        NSLog(@"\n服务器连接失败-->error is %@",failureResult);
        failure(failureResult);
    }];
}


#pragma mark -------------- 设备详情的接口
+ (void)requestWithUrlForGetDeviceInfo:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param success:(void (^)(ACDeviceInfoModel *))success failure:(void (^)(NSString *))failure{
    
    [self GetDataForRequestAndBlockResult:url andRequestParam:param andResult:^(id successResult) {
        ACDeviceInfoModel * infoDeviceModel = [ACDeviceInfoModel deviceInfoWithDic:successResult[@"body"]];
        success(infoDeviceModel);
    } andFailureBlock:^(NSString *failureResult) {
        NSLog(@"\n服务器连接失败-->error is %@",failureResult);
        failure(failureResult);
    }];
}



#pragma mark -------------- 设备详情的加油接口
+ (void)requestWithUrlForAddOil:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param success:(void (^)(NSDictionary* ))success failure:(void (^)(NSString *))failure{
    
    [self GetDataForRequestAndBlockResult:url andRequestParam:param andResult:^(id successResult) {
        success(successResult[@"body"]);
    } andFailureBlock:^(NSString *failureResult) {
        NSLog(@"\n服务器连接失败-->error is %@",failureResult);
        failure(failureResult);
    }];
}

#pragma mark -------------- 设备详情的权限转移
+ (void)requestWithUrlForTranistAuthor:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param success:(void (^)(NSInteger))success failure:(void (^)(NSString *))failure{
    [self GetDataForRequestAndBlockResult:url andRequestParam:param andResult:^(id successResult) {
        success([successResult[@"body"][@"result"] intValue]);
    } andFailureBlock:^(NSString *failureResult) {
        NSLog(@"\n服务器连接失败-->error is %@",failureResult);
        failure(failureResult);
    }];
}


#pragma mark -------------- 自定义工作时间
+ (void)requestWithUrlForSetWorkingTime:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param success:(void (^)(NSInteger))success failure:(void (^)(NSString *))failure{
    [self GetDataForRequestAndBlockResult:url andRequestParam:param andResult:^(id successResult) {
        success([successResult[@"body"][@"result"] intValue]);
    } andFailureBlock:^(NSString *failureResult) {
        NSLog(@"\n服务器连接失败-->error is %@",failureResult);
        failure(failureResult);
    }];
}


#pragma mark 设备列表 --------------   获取设备列表的指定数据
+ (void)requestWithUrlForDeviceWithDeviceState:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param andPage:(NSInteger)current_page andState:(NSInteger)state success:(void (^)(NSArray *))success failure:(void (^)(NSString *))failure{
        [self GetDataForRequestAndBlockResult:url andRequestParam:param andResult:^(id successResult) {
            NSArray * resultDic = successResult[@"body"][@"deviceList"];
            NSMutableArray * tempArr = [NSMutableArray array];
            if (resultDic.count > 0) {
                for ( NSDictionary * tempModel in resultDic) {
                    ACDeviceListModel * listModel = [ACDeviceListModel listModelWithDic:tempModel];
                    if (![[NSString stringWithFormat:@"%@",tempModel[@"i_state"]] isEqualToString:@""]) {
                        [tempArr addObject:listModel];
                    }
                }
            }
            success(tempArr);
        } andFailureBlock:^(NSString *failureResult) {
            NSLog(@"\n服务器连接失败-->error is %@",failureResult);
            failure(failureResult);
   }];
}



#pragma mark 设备配置 -------------- 获取AC泵的配置
+ (void)requestWithUrlForGetACConfig:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param andiSFavoConfig:(BOOL)isFavoConfig success:(void (^)(NSDictionary *))success failure:(void (^)(NSString *))failure{
    [self GetDataForRequestAndBlockResult:url andRequestParam:param andResult:^(id successResult) {
        NSArray * resultArr = successResult[@"body"][@"data"];
        if (resultArr.count) {
            success(successResult[@"body"]);
        }else{
            failure(@"无数据");
        }
    } andFailureBlock:^(NSString *failureResult) {
        NSLog(@"\n服务器连接失败-->error is %@",failureResult);
        failure(failureResult);
    }];
}



#pragma mark 设备配置 -------------- 上传AC泵的配置
+ (void)requestWithURLForUploadACConfig:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param success:(void (^)(NSInteger))success failure:(void (^)(NSString *))failure{
 
    NSDictionary * requestParam = @{@"data":[self dictionaryToJson:param[@"data"]],@"i_imei":[param objectForKey:@"i_imei"],@"isSave":[param objectForKey:@"isSave"]};
    [self PostDataForRequestAndBlockResult:url andRequestParam:requestParam andUpload:false andResult:^(id successResult) {
        int result = [[successResult[@"body"] objectForKey:@"result"] intValue];
        success(result);
    } andFailureBlock:^(NSString *failureResult) {
        failure(failureResult);
    }];
}


#pragma mark 设备配置 -------------- 删除推荐配置
+ (void)requestWithURLForDelegateRecommdConfig:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param success:(void (^)(NSInteger))success failure:(void (^)(NSString *))failure{
    
    [self GetDataForRequestAndBlockResult:url andRequestParam:param andResult:^(id successResult) {
        int result = [[successResult[@"body"] objectForKey:@"result"] intValue];
        success(result);
    } andFailureBlock:^(NSString *failureResult) {
         failure(failureResult);
    }];
    
}


#pragma mark 设备配置 -------------- 获取AC泵的推荐配置列表
+ (void)requestWithUrlForGetDefaultConfig:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param success:(void (^)(NSDictionary *))success failure:(void (^)(NSString *))failure{

    [self GetDataForRequestAndBlockResult:url andRequestParam:param andResult:^(id successResult) {
        success(successResult[@"body"]);
    } andFailureBlock:^(NSString *failureResult) {
        NSLog(@"\n服务器连接失败-->error is %@",failureResult);
        failure(failureResult);
    }];
}




#pragma mark 设备列表 -------------- 获取单台设备的GPS
+ (void)requestWithURLForQueryDeviceGPS:(id)obj andUrl:(NSString *)url andParam:(NSDictionary *)param success:(void (^)(PPQueryGpsModel *))success failure:(void (^)(NSString *))failure{
    
    [self PostDataForRequestAndBlockResult:url andRequestParam:param andUpload:false andResult:^(id successResult) {
        PPQueryGpsModel * model = [PPQueryGpsModel queryGpsModelWithDic:successResult[@"body"]];
        success(model);
    } andFailureBlock:^(NSString *failureResult) {
          failure(failureResult);
    }];
}


#pragma mark App更新
+ (void) requestWithUrlForUpdateApp:(NSString *)url success:(void(^)(NSDictionary* versionInfo))success failure:(void(^)(NSString *))failure{
    
    //远程地址
    NSURL *URL = [NSURL URLWithString:url];
    //默认配置
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    //AFN3.0+基于封住URLSession的句柄
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    //请求
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    //下载Task操作
   NSURLSessionDownloadTask *  _downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        // @property int64_t totalUnitCount;     需要下载文件的总大小
        // @property int64_t completedUnitCount; 当前已经下载的大小
        // 给Progress添加监听 KVO
        NSLog(@"下载的大小:%f",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        //- block的返回值, 要求返回一个URL, 返回的这个URL就是文件的位置的路径
        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];
        return [NSURL fileURLWithPath:path];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        //设置下载完成操作
        // filePath就是你下载文件的位置，你可以解压，也可以直接拿来使用
        NSString *imgFilePath = [filePath path];// 将NSURL转成NSString
        // 创建文件管理器
        NSFileManager *fileManager = [[NSFileManager alloc] init];
        NSData *myData = [fileManager contentsAtPath:imgFilePath];
        NSDictionary *infoDic = nil;
        if (myData) {
           infoDic = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:nil];//转换数据格式
        }
      success(infoDic);
    }];
    [_downloadTask resume];
}

#pragma mark   *******************   GET的优化操作  所有的GET请求在此处执行   *******************
/**
 *  所有的GET请求的都执行此方法，然后把回调的结果返回给上一级，由于每个请求所返回的解析形式都不一样，因此，交由发起者解析数据，请求者只做NSDictionary数据结果返回
 *
 *  @param requestUrl 发起请求的url
 *  @param param      携带的参数
 *  @param success    结果
 *  @param failure
     AFNetworkReachabilityStatusUnknown          = -1,
     AFNetworkReachabilityStatusNotReachable     = 0,
     AFNetworkReachabilityStatusReachableViaWWAN = 1,
     AFNetworkReachabilityStatusReachableViaWiFi = 2,
 */
+ (void) GetDataForRequestAndBlockResult:(NSString *) requestUrl andRequestParam:(NSDictionary *)param andResult:(void(^)(id successResult)) success andFailureBlock:(void(^)(NSString * failureResult)) failure{
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; // 开启网络指示器
    AFHTTPSessionManager *_client = [AFHTTPSessionManager manager];
    _client.responseSerializer = [AFHTTPResponseSerializer serializer];                                 // 设置返回数据的解析方式
    _client.responseSerializer = [AFHTTPResponseSerializer serializer];
    __weak typeof (self)weakSelf = self;
    [_client GET:requestUrl parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSMutableDictionary * responeDic = [weakSelf analythClientResponeData:responseObject];
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; // 关闭网络指示器
        
        NSLog(@"%@",responeDic);
        
        if (responeDic == nil && [self judegementAnthorLogin:responseObject]) {
            [UtilToolsClass addDisapperAlert:@"" withMessage:NSLocalizedString(@"账号异地登陆", nil)];
            // 异地登录
            UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
            ACApplicationKeyWindow.rootViewController = [storyBoard instantiateInitialViewController];
            
            return ;
        }
        success(responeDic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)task.response;
        NSInteger responseStatusCode = [httpResponse statusCode];
        
        
        if(responseStatusCode == 404){
            [UtilToolsClass addDisapperAlert:@"" withMessage:NSLocalizedString(@"会话超时,请重新登录", nil)];
            UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
//            [UD setObject:@(1) forKey:@"isAutomaticLogin"];
            ACApplicationKeyWindow.rootViewController = [storyBoard instantiateInitialViewController];
            
            return ;
        }
        NSLog(@"%@",[weakSelf afterExecute:error]);
        failure([weakSelf afterExecute:error]);
    }];
}

#pragma mark 判断是否是被挤下来了
+ (BOOL) judegementAnthorLogin:(id)responseObject{
    BOOL result = false;
    NSString * tempStr =  [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    NSRange strRange_1 =  [tempStr rangeOfString:@"您的账号已在异地登录，是否重新登录"];
    NSRange strRange_2 =  [tempStr rangeOfString:@"重新登录"];
    if (strRange_1.length != 0 || strRange_2.length != 0) {
        result = true;
    }
    return result;
}

#pragma mark 定义登录的时候保存一下cookie
+ (void) saveLoginSession{
    NSArray * allCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    for (NSHTTPCookie* cookie in allCookies) {
        if ([cookie.name isEqualToString:acServerSessionCookie]) {
            NSMutableDictionary * cookieDictionary = [NSMutableDictionary dictionaryWithDictionary:[UD dictionaryForKey:acLocalCookieName]];
            [cookieDictionary setValue:cookie.properties forKey:acCookitDict];
            [UD setObject:cookieDictionary forKey:acLocalCookieName];
            [UD synchronize];
            NSLog(@"cookie : %@",cookie);
            break;
        }
    }
}


#pragma mark   ******************* POST的优化操作   所有的POST请求在此处执行 注意，此请求只是发起普通Post操作  *******************
/**
 *  所有的GET请求的都执行此方法，然后把回调的结果返回给上一级，由于每个请求所返回的解析形式都不一样，因此，交由发起者解析数据，请求者只做NSDictionary数据结果返回
    如果需要上传东西，就把参数upload设置为true，然后在实现文件中，自我扩展。（目前还没有采用到上传操作）
 *
 *  @param requestUrl 发起请求的url
 *  @param param      携带的参数
 *  @param upload      是否是上传操作
 *  @param success    结果
 *  @param failure
 */
+ (void) PostDataForRequestAndBlockResult:(NSString *) requestUrl andRequestParam:(NSDictionary *)param andUpload:(BOOL)upload andResult:(void(^)(id successResult)) success andFailureBlock:(void(^)(NSString * failureResult)) failure{
     [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; // 关闭网络指示器
    AFHTTPSessionManager *_client = [AFHTTPSessionManager manager];
    _client.responseSerializer = [AFHTTPResponseSerializer serializer];                                 // 设置返回数据的解析方式
    _client.responseSerializer = [AFHTTPResponseSerializer serializer];
    __weak typeof (self)weakSelf = self;
    if(upload){
        // 上传操作
    }else{
        // 普通post请求
        [_client POST:requestUrl parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary * responeDic =  [weakSelf analythClientResponeData:responseObject];
            
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; // 关闭网络指示器
            if (responeDic == nil && [self judegementAnthorLogin:responseObject]) {
                // 异地登录
                [UtilToolsClass addDisapperAlert:@"" withMessage:NSLocalizedString(@"账号异地登录",nil)];
                UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
                ACApplicationKeyWindow.rootViewController = [storyBoard instantiateInitialViewController];
                return ;
            }
            success(responeDic);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             NSLog(@"task :%@",task);
            NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)task.response;
            NSInteger responseStatusCode = [httpResponse statusCode];
            if(responseStatusCode == 404){
                [UtilToolsClass addDisapperAlert:@"" withMessage:NSLocalizedString(@"Session超时,请重新登录",nil)];
                UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
//                 [UD setObject:@(1) forKey:@"isAutomaticLogin"];
                ACApplicationKeyWindow.rootViewController = [storyBoard instantiateInitialViewController];
                return ;
            }
              failure([weakSelf afterExecute:error]);
        }];
    }
}

// 字典转json
+ (NSString*)dictionaryToJson:(NSDictionary *)dic{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    NSLog(@"配置上传 : %@",[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}


#pragma mark 转换返回的数据格式
+ (NSMutableDictionary *) analythClientResponeData:(id)responseObject{
    NSString  *jsonStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
    NSLog(@"获取json字符串：原型---->%@  Dic---%@",jsonStr,jsonDic);
    return [jsonDic mutableCopy];
}


#pragma  mark   请求错误后，返回错误的编码
+ (NSString *)afterExecute:(NSError *)error {
    if (error == nil) {
        return nil;
    }
    if ([error code] == NSURLErrorNotConnectedToInternet) {
        // 网络不给力
        return NSLocalizedString(@"网络异常", nil);
    }else if([error code] == NSURLErrorTimedOut) {
        // 请求超时，请稍后再试
        return NSLocalizedString(@"请求超时,请稍后再试", nil);
    }else if([error code] == NSURLErrorBadServerResponse) {
        // 网络无效，页面不存在
        return NSLocalizedString(@"网络无效,页面不存在", nil);
    }
    // 服务器故障，请稍后再试
    return  NSLocalizedString(@"服务器故障,请稍后再试", nil);
}



@end
